package com.example.yichuangyun.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityMainBinding;
import com.example.yichuangyun.dialog.DownloadDialog;
import com.example.yichuangyun.dialog.VersionUpdateDialog;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.VersionModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.mvvm.ui.fragment.SearchCompanyFragment;
import com.example.yichuangyun.receiver.PhoneBroadcastReceiver;
import com.example.yichuangyun.service.MyPhoneService;
import com.example.yichuangyun.ui.fragment.BusinessFragment;
import com.example.yichuangyun.ui.fragment.IndexFragment;
import com.example.yichuangyun.ui.fragment.MineFragment;
import com.example.yichuangyun.ui.fragment.PhoneFragment;
import com.example.yichuangyun.utils.AppUtils;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DownLoadHelper;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.sharedpreference.SPUtil;
import com.example.yichuangyun.widget.easynavigation.view.EasyNavigationBar;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.annotations.Nullable;

/**
 * 主页面
 */
public class MainActivity extends BaseActivity<ActivityMainBinding, BaseViewModel> {

    private long lastPressBackKeyTime = 0;
    private String[] tabText;
    private final int[] selectIcon = {R.mipmap.tab_index_c, R.mipmap.tab_client_c, R.mipmap.tab_dial, R.mipmap.tab_yi_c, R.mipmap.tab_mine_c};
    private final int[] normalIcon = {R.mipmap.tab_index, R.mipmap.tab_client, R.mipmap.tab_dial, R.mipmap.tab_yi, R.mipmap.tab_mine};
    private final ArrayList<Fragment> fragments = new ArrayList<>();
    private PhoneBroadcastReceiver phoneBroadcastReceiver;
    private VersionUpdateDialog versionUpdateDialog;
    private String downApkUrl;
    private final List<String> permissions = new ArrayList<>();
    private Intent mIntent;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        tabText = new String[]{getString(R.string.home), getString(R.string.business), "", getString(R.string.yi_qi_search), getString(R.string.mine)};
        MyApplication.manager.setLogin(true);
        if (!Settings.canDrawOverlays(context)) {
            // 没有悬浮窗权限,跳转申请
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);
        }
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissions.add(Manifest.permission.CALL_PHONE);
        permissions.add(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
        permissions.add(Manifest.permission.READ_PHONE_STATE);
        permissions.add(Manifest.permission.READ_CALL_LOG);
        permissions.add(Manifest.permission.WRITE_CALL_LOG);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES);
            permissions.add(Manifest.permission.READ_MEDIA_AUDIO);
            permissions.add(Manifest.permission.READ_MEDIA_VIDEO);
        }
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().bindCid(SPUtil.getString(Constant.clientIdKey, "")));
        initFragment();
        checkPermission();
        registerReceiver();
        initDialog();
        checkVersionUpdate();
    }

    private void checkPermission() {
        if (!XXPermissions.isGrantedPermission(getApplicationContext(), permissions)) {
            XXPermissions.with(this)
                    .permission(permissions)
                    .request((permissions, all) -> {
                        if (all) {
                            mIntent = new Intent(context, MyPhoneService.class);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                startForegroundService(mIntent);
                            } else {
                                startService(mIntent);
                            }
                        }
                    });
        } else {
            mIntent = new Intent(context, MyPhoneService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(mIntent);
            } else {
                startService(mIntent);
            }
        }
    }

    private void registerReceiver() {
        if (phoneBroadcastReceiver == null) {
            // 手机拨打电话时会发送：android.intent.action.NEW_OUTGOING_CALL的广播
            IntentFilter receiverFilter = new IntentFilter();
            receiverFilter.addAction(Intent.ACTION_CALL);
            phoneBroadcastReceiver = new PhoneBroadcastReceiver();
            registerReceiver(phoneBroadcastReceiver, receiverFilter);
        }
    }

    private void initFragment() {
        IndexFragment indexFragment = new IndexFragment();
        BusinessFragment businessFragment = new BusinessFragment();
        PhoneFragment phoneFragment = new PhoneFragment();
        SearchCompanyFragment searchCompanyFragment = new SearchCompanyFragment();
        MineFragment mineFragment = new MineFragment();
        fragments.add(indexFragment);
        fragments.add(businessFragment);
        fragments.add(phoneFragment);
        fragments.add(searchCompanyFragment);
        fragments.add(mineFragment);
        binding.navigationBar
                .titleItems(tabText)
                .fragmentList(fragments)
                .normalIconItems(normalIcon)
                .selectIconItems(selectIcon)
                .mode(EasyNavigationBar.NavigationMode.MODE_NORMAL)
                .fragmentManager(getSupportFragmentManager())
                .navigationBackground(getColor(R.color.white))
                .tabTextSize(10)
                .navigationHeight(55)
                .normalTextColor(getColor(R.color.color_53719A))
                .selectTextColor(getColor(R.color.color_426FFF))
                .setPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
                        switch (position) {
                            case 0:
                            case 1:
                                requestTranslucentStatusBar(true);
                                break;
                            case 2:
                                phoneFragment.showNumDialog();
                            case 3:
                                requestTranslucentStatusBar(true);
                                break;
                            case 4:
                                requestTranslucentStatusBar(false);
                                break;
                        }
                        beginTransaction.commitNow();
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                })
                .build();
        binding.ivCall.setOnClickListener(v -> {
            setTab(2);
            phoneFragment.showNumDialog();
        });
    }

    /**
     * 检查版本更新
     */
    private void checkVersionUpdate() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getVersionInfo(), new MyObserver<HttpRespond<VersionModel>>() {
            @Override
            protected void onSuccess(HttpRespond<VersionModel> versionModelHttpRespond) {
                if (versionModelHttpRespond.code == Constant.SUCCESS) {
                    if (null != versionModelHttpRespond.data) {
                        int currentVersion = Integer.parseInt(AppUtils.getVersionName(context).replace(".", ""));
                        int serviceVersion = Integer.parseInt(versionModelHttpRespond.data.getVersion().replace(".", ""));
                        if (currentVersion < serviceVersion) {
                            downApkUrl = versionModelHttpRespond.data.getDownYcyAppUrl();
                            versionUpdateDialog.setVersion(versionModelHttpRespond.data.getVersion());
                            versionUpdateDialog.showDialog();
                        }
                    }
                }
            }
        });
    }

    private void initDialog() {
        versionUpdateDialog = new VersionUpdateDialog(this) {
            @Override
            public void confirm() {
                downloadApk(downApkUrl);
                dismissDialog();
            }
        };
    }

    private void downloadApk(String apkUrl) {
        // 截取apk的名称，如yky.apk
        String destFileName = apkUrl.substring(apkUrl.lastIndexOf("/") + 1);
        final File filesDir = getExternalFilesDir("upgrade");
        // 如果文件不存在新建一个
        if (!filesDir.exists()) {
            filesDir.mkdirs();
        }
        final String filePath = filesDir.getPath() + "/";
        DownloadDialog downloadDialog = new DownloadDialog(this);
        downloadDialog.showDialog();
        DownLoadHelper.getInstance()
                .download(apkUrl, filePath, new DownLoadHelper.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(String path) {
                        downloadDialog.dismissDialog();
                        if (!XXPermissions.isGrantedPermission(context, Permission.REQUEST_INSTALL_PACKAGES)) {
                            ToastHelper.show(getString(R.string.install_permission));
                            new Handler().postDelayed(() -> XXPermissions.with(context)
                                    .permission(Permission.REQUEST_INSTALL_PACKAGES)
                                    .request((permissions, all) -> CommonUtil.installAPK(context, filePath + destFileName)), 2000);
                        } else {
                            CommonUtil.installAPK(context, filePath + destFileName);
                        }
                    }

                    @Override
                    public void onDownloading(int progress) {
                        downloadDialog.setProgress(progress);
                    }

                    @Override
                    public void onDownloadFailed() {
                        downloadDialog.dismissDialog();
                    }
                });
    }

    public void setTab(int position) {
        binding.navigationBar.selectTab(position, false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment f : fragments) {
                f.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastPressBackKeyTime < 1500) {
            super.onBackPressed();
        } else {
            lastPressBackKeyTime = System.currentTimeMillis();
            ToastHelper.show(getString(R.string.exit_app));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (phoneBroadcastReceiver != null) {
            unregisterReceiver(phoneBroadcastReceiver);
        }
        if (mIntent != null) {
            stopService(mIntent);
        }
        if (!TextUtils.isEmpty(MyApplication.manager.getToken())) {
            RetrofitHelper.getInstance().execute(RetrofitHelper.getService().bindCid("1"));
        }
    }
}